import React ,{ PropTypes } from 'react'
import { Form, Row, message,  Col, Input, Button, Select, Modal, Message, DatePicker, Icon, Checkbox } from 'antd'
import { fetchPost } from './request'
import {errorNotify} from './common'

const FormItem = Form.Item
const Option = Select.Option
const RangePicker = DatePicker.RangePicker
const CheckboxGroup = Checkbox.Group;

const formItemLayout = {
  labelCol: {span: 7},
  wrapperCol: {span: 17},
};

class BusinessFilter extends React.Component {
  constructor (props) {

    super(props)
    this.getBizFuncList = this.getBizFuncList.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleModelReset = this.handleModelReset.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.resetSearchParmas = this.resetSearchParmas.bind(this)
    this.disabledDate = this.disabledDate.bind(this)

    this.state = {
      smsTypes :[],
      data: [],
      batchNO: [],
      startTime: null,
      endTime: null,
      fileList: [],
      flag: 0,
      appId: null,
      bizs: [],
      servicers: [],
      params: {
        couponType: '1',
        validtimeType: '1',
        startTime: null,
        endTime: null,
      },
      visible: false,
    }
  }

  componentDidMount() {
    this.getAppList()
    this.getServicerList()
    this.getSmsEnum()
  }


  getSmsEnum() {
    fetchPost('/template/getSmsType').then( json => {
      if (json.data != null) {
        this.setState({
          smsTypes : json.data
        });
      }
    });
  }

  getServicerList(){
    fetchPost('/servicer/getAllServicer').then( json => {
      if (json.data != null) {
        this.setState({
          servicers : json.data
        });
      }
    });
  }

  getAppList() {
    fetchPost('/appInfo/getAppInfo').then( json => {
      if (json.data != null) {
        var data = json.data
        this.setState({
          apps: data
        });
      }
    });
  }

  getBizFuncList(appId) {

    var param = null;
    if(appId) {
      param = {}
      param.appId = appId
    }
    this.props.form.resetFields(['bizCode'])
    fetchPost('/bizFunc/getBizFuncList',param).then( json => {
      if (json.data != null) {
        this.setState({
          appId : appId,
          bizs: json.data
        });
      }
    });
  }

  handleSearch() {
    if (!this.state.appId){
      errorNotify('Query failure','Please choose one app')
      return
    }
    const { validateFields } = this.props.form
    validateFields((err, values) => {
      if(!err){
        console.log(values)
        let aa = {}
        if(values.bizFunctionId) {
          aa.bizFunctionId = values.bizFunctionId;
        }
        if(values.servicerCode) {
          aa.servicerCode = values.servicerCode;
        }
        if(values.time) {
          aa.startTime = values.time[0].format('YYYY-MM-DD HH:mm:ss');
          aa.endTime = values.time[1].format('YYYY-MM-DD HH:mm:ss');
        }
        // 因为sendFlag可能会取到0，当取到0时不能直接判断是否为空
        if(values.sendFlag != null) {
          aa.sendFlag = values.sendFlag
        }
        if(values.msgType) {
          aa.msgType = values.msgType
        }
        aa.currentPage = 1;
        console.log(aa)
        this.props.getSearchData(null,aa);
      }
    })
  }
  handleModelReset() {
    const { resetFields } = this.props.form
    resetFields()
    this.setState({
      visible:false
    })
  }

  handleSubmit () {
    let self = this
    this.props.form.validateFields((err, values) => {
      if(!err) {
        let time = values.time
        let params = {}
        if(values.validtimeType !== '1') {
          values.startTime = time[0].format('YYYY-MM-DD HH:mm:ss'),
            values.endTime = time[1].format('YYYY-MM-DD HH:mm:ss')
          delete values.time
        }
        // this.addCoupontemplate(values)
      }
    })
  }

  resetSearchParmas () {
    this.props.form.resetFields()
    this.handleReset()
  }
  handleReset () {
    this.props.form.resetFields()
    this.setState({
      visible: false,
      startTime: null,
      endTime: null,
      params: {
        couponType: '1',
        validtimeType: '1',
        startTime: null,
        endTime: null,
      },
    }, () => {
      // this.props.getData()
    })
  }

  disabledDate(current) {
    // Can not select days before today and today
    return current && current.valueOf() < Date.now();
  }

  render() {
    // this.props.getBizFuncList = this.getBizFuncList
    const bizOptions = this.state.bizs.map(d => <Option value={d.bizId}>{d.bizName}</Option>);
    const servierOptions = this.state.servicers.map(d => <Option value={d.servicerCode}>{d.servicerName}</Option>);
    const SmsTypeOptions = this.state.smsTypes? this.state.smsTypes.map(d => <Option key={d.code}>{d.desc}</Option>) : null;

    const { getFieldDecorator } = this.props.form
    /*if(this.state.flag === 0) {
      this.state.flag = 1;
      fetchPost(`/message/0/filterlist`).then(json => {
        if (json.data && json.code === 0) {
          //   appIds: [],
          //   bizCodes: [],
          //   servicerNames: [],
          let apps = json.data.appList
          let servicers = json.data.servicerList
          let bizs = json.data.bizList;
          this.setState({
            apps: apps,
            bizs: bizs,
            servicers: servicers
          })
        }
      })
    }*/
    return (
      <div>
        <Form
          className="ant-advanced-search-form"
          style={{marginBottom: 20}}>
          <Row gutter={1}>

            <Col span={5}>
              <FormItem {...formItemLayout} label={'Service provider'}>
                {getFieldDecorator('servicerCode',{initialValue : null})(
                  <Select
                    placeholder="Please enter the service provider"
                  >
                    <Option value={null}>All</Option>
                    {servierOptions}
                  </Select>
                )}
              </FormItem>
            </Col>


            {this.props.appId != this.state.appId ?
              this.getBizFuncList(this.props.appId)
              :false}

            <Col span={6}>
              <FormItem {...formItemLayout} label={'Service scenario'}>
                {getFieldDecorator('bizFunctionId',{initialValue : null})(
                  <Select placeholder="Please enter the service scenario">
                    <Option value={null}>All</Option>
                    {bizOptions}
                  </Select>
                )}
              </FormItem>
            </Col>


            <Col span={6}>
              <FormItem {...formItemLayout} label={'Message type'}>
                {getFieldDecorator('msgType',{initialValue : null})(
                  <Select placeholder="Please enter the message type" onSelect={this.recordTypeChange}>
                    <Option value={null}>All</Option>
                    {SmsTypeOptions}
                  </Select>
                )}
              </FormItem>
            </Col>

            <Col span={6}>
              <FormItem {...formItemLayout} label={'Status'}>
                {getFieldDecorator('sendFlag',{initialValue : null})(
                  <Select placeholder="Status">
                    <Option value={null}>All</Option>
                    <Option value={1}>Normal</Option>
                    <Option value={0}>Invalid</Option>
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>

            <Col span={8}>
              <FormItem {...formItemLayout} label={'Last update time'}>
                {getFieldDecorator('time')(
                  <RangePicker
                    style={{width:'120%'}}
                    allowEmpty
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                )}
              </FormItem>
            </Col>

            <Col span={5} style={{float:'right', textAlign: 'right'}}>
              <Button type="primary" onClick={this.handleSearch}>Search</Button>
              <Button style={{marginLeft :6}} onClick={this.resetSearchParmas}>Reset</Button>
            </Col>
          </Row>
        </Form>
      </div>
    )
  }
}

export default Form.create()(BusinessFilter)
